function All() {
}

import {useFlowStore} from '../stores/flow';

let flowStore = useFlowStore();
const step2FormList = computed(() => {
	return flowStore.step2.formRule || [];
});
// 递归展平表单项，处理包含children的情况
function flattenFormItems(items) {
	const flattened = [];
	
	if (!items || !Array.isArray(items)) {
		return flattened;
	}

	items.forEach((item) => {
		// 如果有子组件，递归处理子组件
		if (item.children && Array.isArray(item.children)) {
			flattened.push(...flattenFormItems(item.children));
		} else if (item.field) {
			// 只添加有field的表单项
			flattened.push(item);
		}
	});

	return flattened;
}

const formIdObj = computed(() => {
	var obj = {};
	
	// 使用递归函数处理表单项（包括子组件）
	const flattened = flattenFormItems(step2FormList.value);
	
	for (var item of flattened) {
		obj[item.field] = item;
	}
	obj['root'] = {
		name: '发起人',
		type: 'SelectUser',
	};
	return obj;
});

All.prototype = {
	timer: '',
	debounce(fn, delay = 500) {
		var _this = this;
		return function (arg) {
			//获取函数的作用域和变量
			let that = this;
			let args = arg;
			clearTimeout(_this.timer); // 清除定时器
			_this.timer = setTimeout(function () {
				fn.call(that, args);
			}, delay);
		};
	},
	setCookie(val) {
		//cookie设置[{key:value}]、获取key、清除['key1','key2']
		for (var i = 0, len = val.length; i < len; i++) {
			for (var key in val[i]) {
				document.cookie = key + '=' + encodeURIComponent(val[i][key]) + '; path=/';
			}
		}
	},
	getCookie(name) {
		var strCookie = document.cookie;
		var arrCookie = strCookie.split('; ');
		for (var i = 0, len = arrCookie.length; i < len; i++) {
			var arr = arrCookie[i].split('=');
			if (name == arr[0]) {
				return decodeURIComponent(arr[1]);
			}
		}
	},
	clearCookie(name) {
		var myDate = new Date();
		myDate.setTime(-1000); //设置时间
		for (var i = 0, len = name.length; i < len; i++) {
			document.cookie = '' + name[i] + "=''; path=/; expires=" + myDate.toGMTString();
		}
	},
	arrToStr(arr) {
		if (arr) {
			return arr
				.map((item) => {
					return item.name;
				})
				.toString();
		}
	},
	toChecked(arr, elem, key = 'id') {
		var isIncludes = this.toggleClass(arr, elem, key);
		!isIncludes ? arr.push(elem) : this.removeEle(arr, elem, key);
	},
	checkApproval(nodeConfig) {
		if (nodeConfig.assignedType == 1) {
			//指定成员
			if (nodeConfig.nodeUserList.length == 0) {
				return false;
			}
		} else if (nodeConfig.assignedType == 3) {
			//指定角色
			if (nodeConfig.nodeUserList.length == 0) {
				return false;
			}
		} else if (nodeConfig.assignedType == 8 && nodeConfig.formUserId.length == 0) {
			//表单
			return false;
		} else if (nodeConfig.assignedType == 10) {
			//流程表达式
			if (!nodeConfig.assignExpress || nodeConfig.assignExpress.trim().length == 0) {
				return false;
			}
		}

		//审批人为空
		if (nodeConfig.nobody?.handler === 'TO_USER' && nodeConfig.nobody.assignedUser.length === 0) {
			return false;
		}

		return true;
	},
	setApproverStr(nodeConfig) {
		if (nodeConfig.assignedType == 1) {
			//指定成员
			if (nodeConfig.nodeUserList.length >= 1) {
				return nodeConfig.nodeUserList.map((res) => res.name).join(',');
			} else {
				return '';
			}
		} else if (nodeConfig.assignedType == 3) {
			//指定角色
			if (nodeConfig.nodeUserList.length >= 1) {
				return nodeConfig.nodeUserList.map((res) => res.name).join(',');
			} else {
				return '';
			}
		} else if (nodeConfig.assignedType == 2) {
			return nodeConfig.deptLeaderLevel == 1 ? '直接部门主管' : '第' + nodeConfig.deptLeaderLevel + '级部门主管';
		} else if (nodeConfig.assignedType == 4) {
			//发起人自选
			return '发起人自选';
		} else if (nodeConfig.assignedType == 5) {
			return '发起人自己';
		} else if (nodeConfig.assignedType == 7) {
			return '到第' + nodeConfig.deptLeaderLevel + '级部门主管终止';
		} else if (nodeConfig.assignedType == 8 && nodeConfig.formUserId.length > 0) {
			//表单
			return '表单：' + nodeConfig.formUserName;
		} else if (nodeConfig.assignedType == 10) {
			//流程表达式
			if (nodeConfig.assignExpress && nodeConfig.assignExpress.trim().length > 0) {
				// 优先使用规则名称显示，如果没有规则名称则显示表达式
				if (nodeConfig.assignExpressName && nodeConfig.assignExpressName.trim().length > 0) {
					return nodeConfig.assignExpressName.trim();
				} else {
					// 如果表达式很长，只显示前面部分
					const expression = nodeConfig.assignExpress.trim();
					if (expression.length > 30) {
						return '流程表达式：' + expression.substring(0, 30) + '...';
					} else {
						return '流程表达式：' + expression;
					}
				}
			} else {
				return '';
			}
		}
		return '';
	},
	dealStr(str, obj) {
		let arr = [];
		let list = str.split(',');
		for (var elem in obj) {
			list.map((item) => {
				if (item == elem) {
					arr.push(obj[elem].value);
				}
			});
		}
		return arr.join('或');
	},
	conditionStr(nodeConfig, index) {
		var conditionNode = nodeConfig.conditionNodes[index];
		var { conditionList, groupMode, conditionType, ruleName, expressionText } = conditionNode;
		
		// 如果是表达式方式（conditionType === 1）
		if (conditionType === 1) {
			if (ruleName && ruleName.trim()) {
				return ruleName.trim();
			} else if (expressionText && expressionText.trim()) {
				// 如果没有规则名称但有表达式，显示表达式的简短版本
				const expression = expressionText.trim();
				if (expression.length > 30) {
					return '表达式：' + expression.substring(0, 30) + '...';
				} else {
					return '表达式：' + expression;
				}
			} else {
				return index == nodeConfig.conditionNodes.length - 1 ? '其他条件进入此流程' : '请设置表达式';
			}
		}
		
		// 条件组方式的原有逻辑
		if (conditionList.length == 0) {
			return index == nodeConfig.conditionNodes.length - 1 ? '其他条件进入此流程' : '请设置条件';
		} else {
			var groupConArr = [];
			for (var groupCondition of conditionList) {
				let mode = groupCondition.mode;

				var conArr = [];

				for (var con of groupCondition.conditionList) {
					const { key, expression, value } = con;
					if (!key) {
						continue;
					}

					let valueElement = formIdObj.value[key];
					if (!valueElement) {
						continue; // 如果找不到对应的表单元素，跳过这个条件
					}
					var name = valueElement.title || valueElement.name;

					var valueShow = value;
					if (valueElement.type === 'SelectUser' || valueElement.type === 'SelectDept' || valueElement.type === 'OrgSelector') {
						valueShow = value.map((res) => res.name).join(',');
					} else if (valueElement.type === 'SingleSelect') {
						valueShow =  value.map(res=>res.value).join(",")
					} else {
						if (!valueShow) {
							valueShow = '?';
						}
					}

					if (expression === '==') {
						conArr.push(name + ' 等于 ' + valueShow);
					} else if (expression === 'in') {
						conArr.push(name + ' 属于 ' + valueShow);
					} else if (expression === 'notin') {
						conArr.push(name + ' 不属于 ' + valueShow);
					} else if (expression === '!=') {
						conArr.push(name + ' 不等于 ' + valueShow);
					} else if (expression === '>') {
						conArr.push(name + ' 大于 ' + valueShow);
					} else if (expression === '>=') {
						conArr.push(name + ' 大于等于 ' + valueShow);
					} else if (expression === '<') {
						conArr.push(name + ' 小于 ' + valueShow);
					} else if (expression === '<=') {
						conArr.push(name + ' 小于等于 ' + valueShow);
					} else if (expression === 'contain') {
						conArr.push(name + " 包含 " + valueShow);
					} else if (expression === 'notcontain') {
						conArr.push(name + " 不包含 " + valueShow);
					}
				}

				if (mode) {
					let s = conArr.join(' 且 ');
					if (conArr.length > 0) {
						groupConArr.push('(' + s + ')');
					}
				} else {
					let s = conArr.join(' 或 ');
					if (conArr.length > 0) {
						groupConArr.push('(' + s + ')');
					}
				}
			}

			return groupConArr.length > 0
				? groupConArr.join(groupMode ? ' 且 ' : ' 或 ')
				: index == nodeConfig.conditionNodes.length - 1
				? '默认条件'
				: '请设置条件1112';
		}
	},
	copyerStr(nodeConfig) {
		if (nodeConfig.nodeUserList?.length != 0) {
			return this.arrToStr(nodeConfig.nodeUserList);
		}
	},
};

// 导出 flattenFormItems 函数供其他组件使用
export { flattenFormItems };

export default new All();
